#include "stack.h"
#define _CRT_SECURE_NO_WARNINGS 1

void StackInit(Stack* ps)
{
	assert(ps);
	ps->_a = NULL;
	ps->_capacity = 0;
	ps->_top = 0;
}

void StackPush(Stack* ps, STDataType data)
{
	assert(ps);
	if (ps->_top == ps->_capacity)
	{
		ps->_capacity  = ps->_capacity == 0 ? 4 : 2 * ps->_capacity * 2;
		ps->_a = (STDataType*)realloc(ps->_a, ps->_capacity * sizeof(STDataType));
		if(!ps->_a)
		{
			perror("Realloc failed");
			return;
		}
	}

	ps->_a[ps->_top] = data;
	ps->_top++;
}

void StackPop(Stack* ps)
{
	if(!StackEmpty(ps))
		ps->_top--;
}

STDataType StackTop(Stack* ps)
{
	return ps->_a[ps->_top - 1];
}

int StackSize(Stack* ps)
{
	return ps->_top;
}

int StackEmpty(Stack* ps)
{
	return !ps->_top;
}

void StackDestroy(Stack* ps)
{
	free(ps->_a);
	ps->_a = NULL;
	ps->_top = ps->_capacity = 0;
}

bool isValid(char* s) 
{
	Stack st;
	StackInit(&st);
	for (int i = 0; s[i]; i++)
	{
		if (s[i] == '(' || s[i] == '[' || s[i] == '{')
			StackPush(&st, s[i]);
		else
		{
			if ((StackTop(&st) == '(' && s[i] == ')') || (StackTop(&st) == '[' && s[i] == ']') || (StackTop(&st) == '{' && s[i] == '}') ) StackPop(&st);
			else return false;
		}
	}
	if (StackEmpty(&st)) return true;
	else return false;
}
